﻿using LitJson;
using LPY.LeHealth.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WxPayAPI;

namespace LPY.LeHealth.WebSite.Controllers
{
    public class WeChatPayController : Controller
    {
        private JsApiPayForMvc api;
        private OrderService orderService;

        public WeChatPayController()
        {
             api = new JsApiPayForMvc(System.Web.HttpContext.Current);
             orderService = new OrderService();
        }

        //public ActionResult ShoppingCart()
        //{
        //    return View();
        //}

        /// <summary>
        /// 获取OpenId
        /// </summary>
        /// <returns></returns>
        //public JsonResult GetOpenId()
        //{
        //    Common.JsonMessage jm = new Common.JsonMessage();
        //    jm.Code = 0;

        //    api.GetOpenidAndAccessToken();
            
        //    if(!string.IsNullOrEmpty(api.openid))
        //    {
        //        jm.Code = 1;
        //        jm.Data = api.openid;
        //    }

        //    return Json(jm);
        //}

        /// <summary>
        /// 获取微信支付参数
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPayParameters(int orderId, string openId)
        {
            Common.JsonMessage jm = new Common.JsonMessage();

            try
            {
                var orderInfo = orderService.GetById(orderId);

                JsApiPayForMvc api = new JsApiPayForMvc(System.Web.HttpContext.Current);
                api.openid = openId;
                api.total_fee =(int)(orderInfo.SumPrice * 100);// 1;//todo: (int)orderInfo.SumPrice * 100;// total_fee;

                //根据orderId获取商品信息
                WeChatOrder order = new WeChatOrder();
                order.body = "体检套餐";//显示在微信支付记录上的信息：商品和商品详情
                order.attach = "体检套餐..";
                order.goods_tag = "体检套餐...";
                order.total_fee = (int)(orderInfo.SumPrice * 100);//todo: (int)orderInfo.SumPrice * 100;// (int)total_fee;// 1;//fen
                order.trade_no = orderInfo.PayCode;//交易号

                //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数,微信的价格是分
                WxPayData unifiedOrderResult = api.GetUnifiedOrderResult(order);
                var wxJsApiParam = api.GetJsApiParameters();//获取H5调起JS API参数                    
                //Log.Debug("Send", "wxJsApiParam : " + wxJsApiParam);

                NLog.LogManager.GetCurrentClassLogger().Debug("获取微信支付参数wxJsApiParam：" + wxJsApiParam);

                jm.Code = 1;
                jm.Data = wxJsApiParam;
            }
            catch (Exception ex)
            {
                //Log.Error("Error", ex.Message);
                NLog.LogManager.GetCurrentClassLogger().Debug("获取微信支付参数异常：" + ex.Message);
                jm.Code = 0;
                jm.Data = ex.Message;
            }

            return Json(jm,JsonRequestBehavior.AllowGet);
        }

        //通知回调
        public JsonResult Notify()
        {
            ResultNotify resultNotify = new ResultNotify(System.Web.HttpContext.Current);
            resultNotify.ProcessNotify();

            return null;
        }

        /// <summary>
        /// 生成微信支付JsApi调用信息
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <param name="total_fee">订单金额</param>
        /// <returns></returns>
        public ActionResult PrePay(int oid /*string orderId,int total_fee*/)
        {
            NLog.LogManager.GetCurrentClassLogger().Debug("微信支付PrePay，oid：" + oid);

            Common.JsonMessage jm = new Common.JsonMessage();
            //string host = Request.Url.Host;
            //string path = Request.Path;

            //回调地址
            string redirect_uri = WxPayAPI.WxPayConfig.Domain + "WeChatPay/PayCallBack?oid=" + oid;// HttpUtility.UrlEncode("http://" + host + path);//这是一个坑

            NLog.LogManager.GetCurrentClassLogger().Debug("回调地址：" + redirect_uri);

            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("redirect_uri", redirect_uri);
            data.SetValue("response_type", "code");
            data.SetValue("scope", "snsapi_base");
            data.SetValue("state", "STATE" + "#wechat_redirect");
            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();

            //HttpClientHelper hch = new HttpClientHelper();
            //var result= hch.checkUrlCanReached(url);
            //result.RawUrl

            NLog.LogManager.GetCurrentClassLogger().Debug("微信跳转地址：" + url);

            Response.Redirect(url);
            //HttpClientHelper hch = new HttpClientHelper();
            //var result = hch.checkUrlCanReached(url);

            if (Session["OpenId"]!=null)
            {
                //return Session["OpenId"].ToString();
            }

            return Content("OK");
        }

        public ActionResult PayCallBack(int oid)
        {
            //Common.JsonMessage jm = new Common.JsonMessage();

            //JsApiPay api = new JsApiPay();
            //api.GetOpenidAndAccessTokenFromCode(code);

            //string url = "http://zsl.s1.natapp.cc/example/JsApiPayPage.aspx?openid=" + api.openid + "&total_fee=" + total_fee;
            //Response.Redirect(url);
            //return null;

            string code = Request.QueryString["code"];

            NLog.LogManager.GetCurrentClassLogger().Debug("PayCallBack,接收Code：" + code);

            //构造获取openid及access_token的url
            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);
            data.SetValue("secret", WxPayConfig.APPSECRET);
            data.SetValue("code", code);
            data.SetValue("grant_type", "authorization_code");
            string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

            NLog.LogManager.GetCurrentClassLogger().Debug("获取Access_token的Url请求：" + url);

            //请求url以获取数据
            string result = HttpService.Get(url);
            //HttpClientHelper hch = new HttpClientHelper();
            //var hc = hch.checkUrlCanReached(url);
            //string result = "";

            //保存access_token，用于收货地址获取
            JsonData jd = JsonMapper.ToObject(result);
            var access_token = (string)jd["access_token"];
            //获取用户openid
            var openid = (string)jd["openid"];

            NLog.LogManager.GetCurrentClassLogger().Debug("返回信息，access_token：{0},openid：{1}", access_token,openid);

            //OpenId保存到Session里
            //Session["OpenId"] = openid;

            //url = "http://zsl.s1.natapp.cc/example/JsApiPayPage.aspx?openid=" + openid + "&total_fee=" + total_fee;
            //Response.Redirect(url);

            //if(!string.IsNullOrEmpty(openid))
            //{
            //    jm.Code = 1;
            //    jm.Msg = "获取到OpenId";
            //    jm.Data = openid;
            //}
            //else
            //{
            //    jm.Code = 0;
            //    jm.Msg = "未获取到OpenId";
            //}

            //return Json(jm);

            var order = orderService.GetById(oid);

            ViewBag.OpenId = openid;
            ViewBag.Price = order.SumPrice;//todo total_fee; 
            ViewBag.OrderId = oid;
            ViewBag.OrderCode= order.Ordercode;
            ViewBag.PayCode= order.PayCode;
            return View("ShoppingCart");

            //return Content(openid);
        }
	}
}